package com.shop.cereshop.app.service.sos.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shop.cereshop.app.dao.sos.CereSosPhoneDAO;
import com.shop.cereshop.app.service.sos.CereSosPhoneService;
import com.shop.cereshop.commons.domain.sos.CereSosPhone;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 一键急救电话-客户端服务实现
 */
@Service
public class CereSosPhoneServiceImpl implements CereSosPhoneService {

    @Autowired
    private CereSosPhoneDAO cereSosPhoneDAO;

    @Override
    public CereSosPhone getByCityCode(String cityCode) {
        String normalized = normalizeCityCode(cityCode);
        if (StringUtils.isBlank(normalized)) {
            return null;
        }
        CereSosPhone phone = cereSosPhoneDAO.selectOne(
                Wrappers.<CereSosPhone>lambdaQuery().eq(CereSosPhone::getCityCode, normalized));
        if (phone == null && normalized.length() == 6 && normalized.endsWith("00")) {
            String parentCode = normalized.substring(0, 4);
            phone = cereSosPhoneDAO.selectOne(
                    Wrappers.<CereSosPhone>lambdaQuery().eq(CereSosPhone::getCityCode, parentCode));
        }
        return phone;
    }

    private String normalizeCityCode(String cityCode) {
        if (StringUtils.isBlank(cityCode)) {
            return null;
        }
        String digits = cityCode.trim().replaceAll("\\D", "");
        if (digits.length() == 4) {
            return digits + "00";
        }
        if (digits.length() >= 6) {
            return digits.substring(0, 6);
        }
        return digits;
    }
}

